﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using MagicKey.Components.AccessManager;
using MagicKey.Components.Database;
using MagicKey.Components.UserManager;
using MagicKey.Interfaces;

namespace MagicKey.UserInterface
{
    /// <summary>
    /// Interaktionslogik für Rechteverwalten.xaml
    /// </summary>
    public partial class ManageAuthorizations : Window
    {

        #region Fields
        MagicDatabase _magicDatabase = new MagicDatabase();
        IAccessManager _accessManager = new AccessManager();
        private IUserManager _userManager = new UserManager();
        private List<User> allUsers;
        private List<string> usersWithAuth;
        private List<string> usersWithoutAuth;
        private List<int> listUserIdToRemove;
        private string selectedFile;
        private User masterUser;
        private bool saved = true;

        #endregion

        #region Constructor
        public ManageAuthorizations(Fileviewer fileviewer)
        {
            InitializeComponent();
            // The following line enables the tremble effect for the current
            // window when clicking on the main window
            this.Owner = fileviewer;

            selectedFile = (string)fileviewer.FileListBox.SelectedItem;

           // allUsers = fileviewer.AllUsers;
            this._userManager.LoadAllUsers();
            allUsers = ((UserManager)this._userManager).Users;

            masterUser = fileviewer.MasterUser;
            usersWithoutAuth = new List<string>();
            usersWithAuth = new List<string>();
            Init();
        }
        #endregion

        #region Methods

        public void Init()
        {
            this.CurrentFileLabel.Content += " " + selectedFile;
            
            foreach (User u in allUsers)
            {
                if (u.OtherUserFiles.Contains(selectedFile))
                {
                    usersWithAuth.Add(u.Name);
                }
                else
                {
                    usersWithoutAuth.Add(u.Name);
                }
            }

            try
            {
                usersWithAuth.Remove(masterUser.Name);
                usersWithoutAuth.Remove(masterUser.Name);
            }
            catch (Exception)
            {
               // Do nothing
            }
            
            this.RefreshfileList();
        }

        private void RefreshfileList()
        {
            this.ListUserWithAuthorizationBox.ItemsSource = this.usersWithAuth;
            this.ListUserNoAuthorizationBox.ItemsSource = this.usersWithoutAuth;
        }

        #endregion

        #region EventChangedMethods
        private void AddAuthorization_Click(object sender, RoutedEventArgs e)
        {
            List<string> usersWithoutAuth = new List<string>();
            List<string> usersWithAuth = new List<string>();

            foreach (string s in this.usersWithoutAuth)
            {
                usersWithoutAuth.Add(s);
            }

            foreach (string s in this.usersWithAuth)
            {
                usersWithAuth.Add(s);
            }

            if (ListUserNoAuthorizationBox.SelectedIndex != -1)
            {
                int selectedIndex = this.ListUserNoAuthorizationBox.SelectedIndex;
                string selectedUser = (string)this.ListUserNoAuthorizationBox.SelectedItem;

                this.usersWithAuth = null;
                this.usersWithoutAuth = null;

                usersWithAuth.Add(selectedUser);
                usersWithoutAuth.RemoveAt(selectedIndex);

                this.usersWithAuth = usersWithAuth;
                this.usersWithoutAuth = usersWithoutAuth;

                RefreshfileList();
            }
            else
            {
                MessageBox.Show("Please select one user to add!", "Authorization",
                                      MessageBoxButton.OK, MessageBoxImage.Exclamation);
            }

        }
        private void AddAuthorizationToAll_Click(object sender, RoutedEventArgs e)
        {
            int count = this.ListUserNoAuthorizationBox.Items.Count;
            if ( count != 0)
            {
                string msg = "Do you really want to add all users?";
                MessageBoxResult result = MessageBox.Show(msg, "Manage authorizations",
                    MessageBoxButton.YesNo, MessageBoxImage.Question);
                if (result == MessageBoxResult.Yes)
                {

                    List<string> usersWithoutAuth = new List<string>();
                    List<string> usersWithAuth = new List<string>();

                    foreach (string s in this.usersWithAuth)
                    {
                        usersWithAuth.Add(s);
                    }

                    foreach (string s in this.usersWithoutAuth)
                    {
                        usersWithAuth.Add(s);
                    }


                    this.usersWithAuth = null;
                    this.usersWithoutAuth = null;

                    this.usersWithAuth = usersWithAuth;
                    this.usersWithoutAuth = usersWithoutAuth;

                    RefreshfileList();
                }
            }
            else if (count == 1)
            {
                this.AddAuthorization_Click(sender, new RoutedEventArgs());
            }
        }

        private void RemoveAuthorization_Click(object sender, RoutedEventArgs e)
        {
            List<string> usersWithoutAuth = new List<string>();
            List<string> usersWithAuth = new List<string>();

            foreach (string s in this.usersWithoutAuth)
            {
                usersWithoutAuth.Add(s);
            }

            foreach (string s in this.usersWithAuth)
            {
                usersWithAuth.Add(s);
            }

            if (ListUserWithAuthorizationBox.SelectedIndex != -1)
            {
                int selectedIndex = this.ListUserWithAuthorizationBox.SelectedIndex;
                string selectedUser = (string)this.ListUserWithAuthorizationBox.SelectedItem;

                this.usersWithAuth = null;
                this.usersWithoutAuth = null;

                usersWithoutAuth.Add(selectedUser);
                usersWithAuth.RemoveAt(selectedIndex);

                this.usersWithAuth = usersWithAuth;
                this.usersWithoutAuth = usersWithoutAuth;

                RefreshfileList();
            }
            else
            {
                MessageBox.Show("Please select one user to remove!", "Authorization",
                                      MessageBoxButton.OK, MessageBoxImage.Exclamation);
            }
        }

        private void RemoveAuthorizationToAll_Click(object sender, RoutedEventArgs e)
        {
            int count = this.ListUserWithAuthorizationBox.Items.Count;
            if ( count != 0)
            {
                string msg = "Do you really want to remove all users?";
                MessageBoxResult result = MessageBox.Show(msg, "Manage authorizations",
                    MessageBoxButton.YesNo, MessageBoxImage.Question);
                if (result == MessageBoxResult.Yes)
                {

                    List<string> usersWithoutAuth = new List<string>();
                    List<string> usersWithAuth = new List<string>();

                    foreach (string s in this.usersWithoutAuth)
                    {
                        usersWithoutAuth.Add(s);
                    }

                    foreach (string s in this.usersWithAuth)
                    {
                        usersWithoutAuth.Add(s);
                    }


                    this.usersWithAuth = null;
                    this.usersWithoutAuth = null;

                    this.usersWithAuth = usersWithAuth;
                    this.usersWithoutAuth = usersWithoutAuth;

                    RefreshfileList();
                }
            }
            else if (count == 1)
            {
                this.RemoveAuthorization_Click(sender, new RoutedEventArgs());
            }
        }


        private void ListUserNoAuthorizationBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

        }

        private void ListUserWithAuthorizationBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

        }


        private void Save_Click(object sender, RoutedEventArgs e)
        {
            
            List<int> listUserId = new List<int>();
            List<int> listUserIdToRemove = new List<int>();
           
            MagicDatabase magicDatabase = new MagicDatabase();
            int fileId = magicDatabase.GetFileId(this.selectedFile);

            foreach (string s in usersWithAuth)
            {
                foreach (User u in allUsers)
                {
                    if (u.Name.Equals(s))
                    {
                        listUserId.Add(u.Id);
                        break;
                    }
                }
            }

            foreach (string s in usersWithoutAuth)
            {
                foreach (User u in allUsers)
                {
                    if (u.Name.Equals(s))
                    {
                        listUserIdToRemove.Add(u.Id);
                        break;
                    }
                }
            }

            foreach (int i in listUserId)
            {
                magicDatabase.DatabaseName = "dba";
                magicDatabase.InsertAuthorization(this.masterUser.Id, i, fileId);
                magicDatabase.DatabaseName = "dba2";
                magicDatabase.InsertAuthorization(this.masterUser.Id, i, fileId);
            }

            foreach (int i in listUserIdToRemove)
            {
                magicDatabase.RemoveAuthorization(i);
            }
            this.RefreshfileList();
            saved = false;
            this.Close();
        }

        private void Cancel_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private void ManageAuthorizations_OnClosing(object sender, CancelEventArgs e)
        {
            if (saved)
            {
                string msg = "Do you really want to cancel?";
                MessageBoxResult result = MessageBox.Show(msg, "Manage authorizations",
                    MessageBoxButton.YesNo, MessageBoxImage.Question);
                if (result == MessageBoxResult.No)
                {
                    // If user doesn't want to close, cancel closure
                    ((Fileviewer)this.Owner).RefreshfileList();
                    e.Cancel = true;
                }
                else
                {
                    Owner.Focus();
                    e.Cancel = false;
                }
            }
            else
            {
                MessageBox.Show("Saving was successfull.", "Manage authorizations",
                    MessageBoxButton.OK, MessageBoxImage.Information);
                Owner.Focus();
                e.Cancel = false;
            }
        }

        private void ListUserNoAuthorizationBox_OnMouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            this.AddAuthorization_Click(sender, new RoutedEventArgs());
        }

        private void ListUserWithAuthorizationBox_OnMouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            this.RemoveAuthorization_Click(sender, new RoutedEventArgs());
        }

        #endregion

       
       }
}